package com.faya.green.service.impl;

import com.faya.green.abnormal.ServiceException;
import com.faya.green.common.Constant;
import com.faya.green.dao.authority.AuthorityDao;
import com.faya.green.dao.authority.AuthorityRoleDao;
import com.faya.green.dao.authority.RoleDao;
import com.faya.green.enumeration.StatusEnum;
import com.faya.green.model.Authority;
import com.faya.green.model.AuthorityRole;
import com.faya.green.model.Role;
import com.faya.green.model.User;
import com.faya.green.service.RoleService;
import com.faya.green.utils.CommonUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author ：LX
 * 创建时间： 2018/8/24. 23:57
 * 地点：广州
 * 目的: 角色
 * 备注说明：
 */
@Service
public class RoleServiceImpl implements RoleService {

    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private RoleDao roleDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private AuthorityRoleDao authorityRoleDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private AuthorityDao authorityDao;



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRole(Role role) {
        role.setId(UUID.randomUUID().toString());
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        if (role.getSort() == null){
            role.setSort(1);
        } else {
            //TODO 后期加上当前用户的sort级别 + 1，存在多个角色，暂无解决方案
            //role.setSort();
        }

        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        role.setCreateUser(user.getId());
        role.setUpdateUser(user.getId());
        if (CommonUtils.checkNull(role.getStatus())){
            role.setStatus(StatusEnum.STATUS_ADD.getCode());
        }

        roleDao.addRole(role);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRole(Role role) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        role.setCreateUser(user.getId());
        role.setUpdateTime(new Date());
        roleDao.updateRole(role);
    }

    @Override
    public Role getRoleById(String id) {
        return roleDao.getRoleById(id);
    }

    @Override
    public List<Role> getRoleList() {
        return roleDao.getRoleList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delLogicRole(String roleId) {
        Role role = roleDao.getRoleById(roleId);
        if (role == null){
            throw new ServiceException("未找到对应的角色");
        }
        if (Constant.ROLE_BASE.equals(role.getId())){
            throw new ServiceException("核心角色不能删除");
        }
        role.setStatus(StatusEnum.STATUS_DELETE.getCode());
        //roleDao.updateRole(role);
        roleDao.delRole(role.getId());

        //对相关的权限对应关系进行删除
        List<AuthorityRole> authorityRoleList = authorityRoleDao.getAuthorityRoleByRoleId(roleId);
        if (authorityRoleList != null && authorityRoleList.size() > 0){
            for (AuthorityRole authorityRole : authorityRoleList){
                authorityRole.setStatus(StatusEnum.STATUS_DELETE.getCode());
                //authorityRoleDao.updateAuthorityRole(authorityRole);
                authorityRoleDao.delAuthorityRoleById(authorityRole.getId());
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrUpdRole(Role role, String[] authorArr) {
        if (role == null){
            throw new ServiceException("没有需要添加的角色");
        }

        String name = role.getName();
        if (Constant.ROLE_BASE.equals(role.getId())){
            throw new ServiceException("核心角色不能删除");
        }

        if (CommonUtils.checkNull(role.getId())){
            Role sqlRole = roleDao.getRoleByName(name);
            if (sqlRole != null){
                throw new ServiceException("该角色已经存在，不能再次添加");
            }
            addRole(role);
        } else {
            updateRole(role);
            //将旧的关系先删除
            authorityRoleDao.delAuthorityRoleByRoleId(role.getId());
        }

        //权限增加
        if (authorArr != null && authorArr.length > 0){
            for (String authorId : authorArr){
                Authority authority = authorityDao.getAuthorityById(authorId);
                if (authority != null){
                    AuthorityRole authorityRole = new AuthorityRole();
                    authorityRole.setId(UUID.randomUUID().toString());
                    authorityRole.setRoleId(role.getId());
                    authorityRole.setAuthorityId(authorId);
                    authorityRole.setStatus(StatusEnum.STATUS_ADD.getCode());
                    authorityRole.setCreateTime(new Date());
                    authorityRole.setUpdateTime(new Date());
                    authorityRoleDao.addAuthorityRole(authorityRole);
                }
            }
        }
    }

    @Override
    public List<Role> getRoleByUserId(String createUser) {
        return roleDao.getRoleByUserId(createUser);
    }

    @Override
    public List<Role> getUserByRole(String userId) {
        return roleDao.getUserByRole(userId);
    }

    @Override
    public List<Role> getUserByRoleCreatRole(String userId) {
        return roleDao.getUserByRoleCreatRole(userId);
    }
}
